import Vue from 'vue'
import SCHEME from '@/static/scheme'
import { getToken } from '@/utils/user'
import qs from '@/uview-ui/libs/function/queryParams'

/**
 * 解析scheme
 * project^id:5,name:yjl => {
 *  scheme: project
 *  param: {id: 5,name:yjl}
 * }
 */
export function parseScheme(scheme = '') {
  const res = {
    scheme,
    params: {} // 拼接的的路径参数
  }

  const arr = scheme.split('^')

  /* 获取scheme值 */
  res.scheme = arr[ 0 ]

  /* 判断是否有参数 */
  if (arr[ 1 ]) {
    arr[ 1 ].split(',').forEach(paramStr => {
      const param = paramStr.split(':')

      res.params[ param[ 0 ] ] = param[ 1 ]
    })
  }
  return res
}

/**
 * 执行scheme
 * @param {String} scheme scheme值
 * @param {Boolean} closePage 是否关闭当前页
 */
export function actionScheme({ scheme = '', closePage = false, success, fail, complete }) {
  const res = parseScheme(scheme)
  const schemeParam = SCHEME[ res.scheme ] || SCHEME[ 'home' ]

  /* 需要登录，但是未登录 */
  if (schemeParam.needLogin && !getToken()) {
    /* 判断是否需要关闭当前页 */
    if (closePage) {
      Vue.prototype.$router.redirectToLogin({ scheme }, () => {
        Vue.prototype.$msg('需要登录才能使用该功能')
      })
    } else {
      Vue.prototype.$router.navigateToLogin({ scheme }, () => {
        Vue.prototype.$msg('需要登录才能使用该功能')
      })
    }
  } else {
    const pathParam = { ...schemeParam.pathParams, ...res.params }

    /*
      判断类型
      tabPage - tabbar跳转
      miniPage - 小程序二级页面
      miniProgram - 其他小程序
      h5 - webview
    */
    if (schemeParam.type === 'tabPage') { // pages页面需要用uni.switchTab
      uni.switchTab({
        url: `${ schemeParam.path }${ qs(pathParam) }`,
        success, fail, complete
      })
    } else if (schemeParam.type === 'miniPage') {
      if (closePage) { // 需要关闭当前页
        uni.redirectTo({
          url: `${ schemeParam.path }${ qs(pathParam) }`,
          success, fail, complete
        })
      } else { // 一般二级页面跳转
        uni.navigateTo({
          url: `${ schemeParam.path }${ qs(pathParam) }`,
          success, fail, complete
        })
      }
    } else if (schemeParam.type === 'miniProgram') {
      uni.navigateToMiniProgram({
        appId: schemeParam.appId,
        path: pathParam.path,
        envVersion: 'release'
      })
    }
  }
}

/**
 * 格式化scheme，将对象参数写入
 */
export function qsScheme({ scheme, ...params }) {
  let str = `${ scheme }^`

  for (const key in params) {
    str += `${ key }:${ params[ key ] },`
  }
  return str.slice(0, -1) // 最后一个,号不要
}

/**
 * 计算当前路径的scheme
 */
export function getCurrentScheme() {
  // eslint-disable-next-line no-undef
  let currentPath = getCurrentPages()

  currentPath = currentPath[ currentPath.length - 1 ]
  const route = `/${ currentPath.route }`

  let scheme

  for (const key in SCHEME) {
    if (SCHEME[ key ].path === route) {
      scheme = key
      break
    }
  }
  return scheme ? qsScheme({ scheme, ...currentPath.options }) : 'home'
}

/**
 * 根据当前路径计算启动路径, 必须设置scheme，否则直接跳入口页
 */
export function computeStartPath() {
  const scheme = getCurrentScheme()

  return scheme ? `pages/Entry?scheme=${ scheme }` : 'pages/Entry'
}
